package com.youlu.campus.admin.platform;

import com.youlu.campus.admin.auth.entity.SystemRole;
import com.youlu.campus.admin.auth.service.RoleService;
import com.youlu.campus.admin.utils.AuthUtils;
import com.youlu.campus.common.base.RestResult;
import com.youlu.campus.common.base.RestResultBuilder;
import com.youlu.campus.entity.PlatformConfig;
import com.youlu.campus.service.platform.PlatformConfigService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 平台配置
 */
@RestController
public class PlatformConfigController {
    @Autowired
    private PlatformConfigService platformService;

    @Autowired
    private RoleService roleService;

    /**
     * 平台配置 查询
     *
     * @return
     */
    @GetMapping("/platform-config")
    public RestResult getPlatformConfig() {
        PlatformConfig platformConfig = platformService.find();
        return RestResultBuilder.builder().success().data(platformConfig).build();
    }

    /**
     * 更新平台配置
     *
     * @param config
     * @return
     */
    @PostMapping("/platform-config/update")
    public RestResult updatePlatformConfig(@RequestBody PlatformConfig config) {
        return platformService.updateAndVerify(config);
    }

    /**
     * 获取手机验证码
     *
     * @return
     */
    @GetMapping("/platform-config/phone-code")
    public RestResult getPhoneCode() {
        String userId = AuthUtils.getUserId();
        List<SystemRole> roleList = roleService.findAllByUserId(userId);
        List<SystemRole> adminRole = roleList.stream().filter(r -> "admin".equals(r.getIdentifier())).collect(Collectors.toList());
        //判断是否是 管理员  或者 是不是创建者
        if (CollectionUtils.isEmpty(adminRole)) {
            return RestResultBuilder.builder().failure().build();
        }
        platformService.sendSmsMsg();
        return RestResultBuilder.builder().success().build();
    }
}
